package org.realteam.hibernate.test.model.inheritance;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class GenderType implements UserType {

	protected static final Logger log = LogManager.getLogger(GenderType.class);
	
	public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
		return cached;
	}

	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable)value;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return x == y;
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public boolean isMutable() {
		return false;
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		Integer gender = rs.getInt(names[0]);
		return rs.wasNull()? null : Gender.getGender(gender);
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		if(value == null)
			st.setNull(index, Types.SMALLINT);
		else
			st.setInt(index, ((Gender)value).getValue());
	}

	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		throw new UnsupportedOperationException();
	}

	public Class returnedClass() {
		return Gender.class;
	}

	@SuppressWarnings("deprecation")
	public int[] sqlTypes() {
		return new int[]{Types.SMALLINT};
	}

}
